package com.taotao.manager.controller;

import com.taotao.common.util.JsonUtils;
import com.taotao.manager.web.util.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@Controller
public class PictureController {
    @Value("${TAOTAO_IMAGE_SERVER_URL}")
    private String TAOTAO_IMAGE_SERVER_URL;

    @RequestMapping(value = "/pic/upload",produces = MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
    @ResponseBody
    public String fileUpload(MultipartFile uploadFile){
        try {
            //取文件扩展名
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //创建FastDFS客户端
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:fastdfs.conf");
            String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            String url = TAOTAO_IMAGE_SERVER_URL+path;
            HashMap<Object, Object> resultMap = new HashMap<>();
            resultMap.put("error", 0);
            resultMap.put("url", url);
            return JsonUtils.objectToJson(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<Object, Object> resultMap=new HashMap<>();
            resultMap.put("error", 1);
            resultMap.put("message", "图片上传失败");
            return JsonUtils.objectToJson(resultMap);
        }
    }
}
